package com.slt.android.customview.pichandle;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.slt.android.customview.R;

/**
 * Created by dp on 2018/1/9.
 */

public class PicHandleView extends View {
    Bitmap bitmap;
    Matrix matrix = new Matrix();
    private float[] mImageMatrix = new float[9];

    int WIDTH = 200 ,HEIGHT = 200;
    private int COUNT = (WIDTH + 1) * (HEIGHT + 1);
    float orig[] , verts[];
    private float A;
    private float k = 1;
    public PicHandleView(Context context) {
        super(context);
        init(context);
    }

    public PicHandleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PicHandleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        orig = new float[COUNT * 2];
        verts = new float[COUNT * 2];
        bitmap = BitmapFactory.decodeResource(getResources() , R.mipmap.dlrb);

        //像素块处理开始
        float bitmapWidth = bitmap.getWidth();
        float bitmapHeight = bitmap.getHeight();
        int index = 0;
        for (int i = 0; i <= HEIGHT; i++) {
            float fy = bitmapHeight * i / HEIGHT;
            for (int i1 = 0; i1 <= WIDTH; i1++) {
                float fx = bitmapWidth * i1 / WIDTH;
                orig[index *2 +0] = verts[index * 2 +0] = fx;
                orig[index *2 +1] = verts[index * 2 +1] = fy + 100;
                index += 1;
            }
        }
        A = 50;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        initMatrix();
//        canvas.drawBitmap(bitmap , matrix , null);
        flagWave();
        k += 0.1F;
        canvas.drawBitmapMesh(bitmap , WIDTH , HEIGHT , verts , 0 , null , 0 , null);
        invalidate();

    }
    private void flagWave() {
        for (int j = 0; j <= HEIGHT; j++) {
            for (int i = 0; i <= WIDTH; i++) {
                verts[(j * (WIDTH + 1) + i) * 2 + 0] += 0;
                float offsetY =
                        (float) Math.sin((float) i / WIDTH * 2 * Math.PI +
                                Math.PI * k);
                verts[(j * (WIDTH + 1) + i) * 2 + 1] =
                        orig[(j * WIDTH + i) * 2 + 1] + offsetY * A;
            }
        }
    }

    /** matrix的set方法会重置矩阵中所有的值
     * 矩阵的乘法不满足交换率，前乘和后乘有区别*/
    private void initMatrix() {
        matrix.setValues(mImageMatrix);
        matrix.setTranslate(100 , 100);
        matrix.preRotate(45);
    }
}
